package order

import (
	"context"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/pancakebotorder"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPancakebotOrderByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}
type OutletQrInfo struct {
	OutletNo int64  `json:"outlet_no"`
	PayId    string `json:"pay_id"`
	DeviceId uint64 `json:"device_id"`
}

func NewGetPancakebotOrderByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPancakebotOrderByIdLogic {
	return &GetPancakebotOrderByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetPancakebotOrderByIdLogic) GetPancakebotOrderById(in *pancakebot.IDReq) (*pancakebot.PancakebotOrderInfo, error) {
	// 查询订单
	order, err := l.svcCtx.DB.PancakebotOrder.Query().
		Where(pancakebotorder.IDEQ(in.Id)).
		Only(l.ctx)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	// 转换为响应格式
	createdAt := order.CreatedAt.UnixMilli()
	updatedAt := order.UpdatedAt.UnixMilli()
	price := float32(order.Price)

	resp := &pancakebot.PancakebotOrderInfo{
		Id:              &order.ID,
		CreatedAt:       &createdAt,
		UpdatedAt:       &updatedAt,
		UserId:          &order.UserID,
		DeviceId:        &order.DeviceID,
		ComboId:         &order.ComboID,
		ComboName:       &order.ComboName,
		ComboIngredient: []uint64{}, // 配料信息需要从字符串解析或单独存储
		Price:           &price,

		PayStatus: &order.PayStatus,
	}

	// 设置可选字段
	if order.OutletNo != nil {
		outletNo := int64(*order.OutletNo)
		resp.OutletNo = &outletNo
	}

	if order.OutletTime != nil {
		outletTime := order.OutletTime.UnixMilli()
		resp.OutletTime = &outletTime
	}

	// PayOrderId 是 uint64,非零值表示已设置
	if order.PayOrderId != 0 {
		resp.PayOrderId = &order.PayOrderId
	}

	if !order.PayTime.IsZero() {
		payTime := order.PayTime.UnixMilli()
		resp.PayTime = &payTime
	}

	// PayChannelCode 是 string,非空表示已设置
	if order.PayChannelCode != "" {
		resp.PayChannelCode = &order.PayChannelCode
	}

	// PayRefundID 是 uint64,非零值表示已设置
	if order.PayRefundID != 0 {
		resp.PayRefundId = &order.PayRefundID
	}

	// RefundPrice 是 int32,非零值表示已设置
	if order.RefundPrice != 0 {
		resp.RefundPrice = &order.RefundPrice
	}

	if !order.RefundTime.IsZero() {
		refundTime := order.RefundTime.UnixMilli()
		resp.RefundTime = &refundTime
	}

	return resp, nil
}
